package nl.xs4all.dylanschell.deckprinter.services;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Sets
{

    private static final Logger logger = Logger.getLogger("Sets");
    private final Map<String, String> sets = new HashMap<String, String>();
    private final DeckPrinterConfig config;

    public Sets(DeckPrinterConfig config)
    {
        this.config = config;
        logger.log(Level.INFO, "parsing set information.");
        parseSets();
    }

    private void parseSets()
    {
        File folder = config.getDeckPrinterFolder();
        File setsFile = new File(folder, "sets.lst");
        InputStream in = null;
        if (setsFile.isFile())
        {
            try
            {
                in = new FileInputStream(setsFile);
            } catch (FileNotFoundException ex)
            {
                // never happens, since we check
            }
        }
        if (in == null)
        {
            in = Sets.class.getResourceAsStream("/sets.txt");
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        try
        {
            String line;
            try
            {
                while ((line = br.readLine()) != null)
                {
                    parseSetLine(line);
                }
            } catch (IOException e)
            {
                logger.log(Level.WARNING, "Unable to parse set database.", e);
            }
        } finally
        {
            try
            {
                br.close();
            } catch (IOException ignored)
            {
                logger.log(Level.FINEST, "closing stream", ignored);
            }
        }
    }

    private void parseSetLine(String line)
    {
        if (Character.isDigit(line.charAt(0)))
        {
            // set line with date
            line = line.substring(6);
        }
        int eq = line.indexOf('=');
        String name = line.substring(0, eq);
        String code = line.substring(eq + 1);
        sets.put(code, code);
    }

    public String getCanonicalSet(String set)
    {
        if ("ZEN".equals(set))
        {
            return "ZEN";
        }
        if (set == null || set.length() == 0)
        {
            return null;
        }
        String result = sets.get(set);
        if (result != null)
        {
            return result;
        }
        return null;
    }
}